<?php
namespace Home\Controller;
use Think\Controller;

/**
 * 球馆控制
 * 球场控制
 */
class GymnasiumController extends Controller {
	//全局变量区
	/**
     * 布局相关
     * list_each_page_number：每一页列表条数
     */
    public $list_each_page_number = 5;

	//**********进入球馆前球馆列表部分**********//
	/**
	 * 进入球馆页面
	 */
	public function index(){
		$this->display();
	}

	/**
	 * 列出全部球馆
	 */
	public function listAllGymnasium(){
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的球馆条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//信息查询
		$result = $gymnasium->field('gymnasium_id, gymnasium_name, gymnasium_location_bref, gymnasium_picture, gymnasium_phone_number')->limit($start_p, $e_page_num)->select();
		$gymnasiumCount = $gymnasium->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['gymnasium_count'] = $gymnasiumCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 列出当前区下所有的球馆
	 */
	public function listDistrictGymnasium(){
		//从前端获取地理位置信息
		$gymnasium_location['gymnasium_province'] = $_POST['gymnasium_province'];
		$gymnasium_location['gymnasium_city'] = $_POST['gymnasium_city'];
		$gymnasium_location['gymnasium_district'] = $_POST['gymnasium_district'];
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的球馆条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//信息查询
		$result = $gymnasium->where($gymnasium_location)->field('gymnasium_id, gymnasium_name, gymnasium_location_bref, gymnasium_picture, gymnasium_phone_number')->limit($start_p, $e_page_num)->select();
		$gymnasiumCount = $gymnasium->where($gymnasium_location)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['gymnasium_count'] = $gymnasiumCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 离我最近球馆
	 */
	public function listNearCymnasium(){
		//从前端获取地理位置信息
		$gymnasium_location['gymnasium_location_x'] = $_POST['gymnasium_location_x'];
		$gymnasium_location['gymnasium_location_y'] = $_POST['gymnasium_location_y'];
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的球馆条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//转换参数rad_change弧度换算度
		$rad_change = 180 / pi();

		//经纬范围计算
		//维度范围计算
		$gymnasiumDifferenceY = 5 / 111;
		$gymnasiumLocationYLow = $gymnasium_location['gymnasium_location_y'] - $gymnasiumDifferenceY;
		$gymnasiumLocationYHigh = $gymnasium_location['gymnasium_location_y'] + $gymnasiumDifferenceY;
		//经度范围计算
		$gymnasiumDifferenceLowX = 5 / (111 * cos($gymnasiumLocationYLow / $rad_change));
		$gymnasiumDifferenceHighX = 5 / (111 * cos($gymnasiumLocationYHigh / $rad_change));
		$gymnasiumLocationXLow = $gymnasium_location['gymnasium_location_x'] - $gymnasiumDifferenceLowX;
		$gymnasiumLocationXHigh = $gymnasium_location['gymnasium_location_x'] - $gymnasiumDifferenceHighX;

		//信息查询
		$where['gymnasium_location_x'] = array('between', $gymnasiumLocationXLow, $gymnasiumLocationXHigh);
		$where['gymnasium_location_y'] = array('between', $gymnasiumLocationYLow, $gymnasiumLocationYHigh);
		$result = $gymnasium->where($where)->field('gymnasium_id, gymnasium_name, gymnasium_location_bref, gymnasium_picture, gymnasium_phone_number')->limit($start_p, $e_page_num)->select();
		$gymnasiumCount = $gymnasium->where($where)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['gymnasium_count'] = $gymnasiumCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 当前地区球馆搜索
	 */
	public function searchGymnasium(){
		//从前端获取地理位置信息
		$gymnasium_info['gymnasium_province'] = $_POST['gymnasium_province'];
		$gymnasium_info['gymnasium_city'] = $_POST['gymnasium_city'];
		$gymnasium_info['gymnasium_district'] = $_POST['gymnasium_district'];
		$gymnasium_name = $_POST['gymnasium_name'];
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的球馆条数
		$page_num = $_POST['page_num'];  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//信息查询
		$gymnasium_name = "%".$gymnasium_name;
		$gymnasium_info['gymnasium_name'] = array('like', $gymnasium_name."%");
		$result = $gymnasium->where($gymnasium_info)->field('gymnasium_id, gymnasium_name, gymnasium_location_bref, gymnasium_picture, gymnasium_phone_number')->limit($start_p, $e_page_num)->select();
		$gymnasiumCount = $gymnasium->where($gymnasium_location)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['gymnasium_count'] = $gymnasiumCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 在所有球馆中搜索
	 */
	public function searchAllGymnasium(){
		//从前端获取地理位置信息
		$gymnasium_name = $_POST['gymnasium_name'];
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		
		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的球馆条数
		$page_num = $_POST['page_num'];  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//信息查询
		$gymnasium_name = "%".$gymnasium_name;
		$gymnasium_info['gymnasium_name'] = array('like', $gymnasium_name."%");
		$result = $gymnasium->where($gymnasium_info)->field('gymnasium_id, gymnasium_name, gymnasium_location_bref, gymnasium_picture, gymnasium_phone_number')->limit($start_p, $e_page_num)->select();
		$gymnasiumCount = $gymnasium->where($gymnasium_info)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['gymnasium_count'] = $gymnasiumCount;
		$this->ajaxReturn($resultList);
	}

	//**********进入球馆后球场部分**********//
	/**
	 * 球馆详情页面
	 */
	public function courtPage(){
		//从前端获取球馆标识
		$gymnasium_info['gymnasium_id'] = $_GET['gymnasium_id'];

		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		// 实例化用户对象
        $user = M('user_table');

		//查询球馆信息
		$resultGymnasium = $gymnasium->where($gymnasium_info)->find();
		if(!$resultGymnasium){
			$resultList['have_gymnasium'] = 0;
		}else{
			$resultList['have_gymnasium'] = 1;
			//查询馆长信息
			$resultGymnasiumMaster = $user->where($resultGymnasium['gymnasium_master_id'])->find();

			//返回数据组装
			$resultList['resultGymnasium'] = $resultGymnasium;
			$resultList['gymnasium_master_name'] = $resultGymnasiumMaster['name'];
			$resultList['gymnasium_id'] = $gymnasium_id;
		}
		//dump($resultList);
		//return;
		$this->assign('resultList', json_encode($resultList));
		$this->display();
	}
	
	/**
	 * 选定时间后展开球场预定界面
	 * $date：当前时间时间戳
	 * $gymnasium_id：当前球馆id
	 */
	public function courtLoad(){
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		//实例化停馆对象
		$gymnasiumClose = M('gymnasium_close_table');
		//实例化球场对象
		$court = M('court_table');
		//实例化球场预约对象
		$courtBook = M('court_book_table');
		
		$fresultList = array();
		
		//从前端获取时间戳
		$timestamp = $_POST['timestamp'];
		$gymnasium_id = $_POST['gymnasium_id'];

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的球馆条数
		$page_num = $_POST['page_num'];  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//组装查询条件
		$where['close_start_time'] = array('lt', $timestamp);
		$where['close_end_time'] = array('gt', $timestamp);
		$where['gymnasium_id'] = $gymnasium_id;
		//查询闭馆信息
		$result = $gymnasiumClose->where($where)->find();

		//如果不闭馆加载球场选择模板
		if($result){
			//当球馆停馆时不加载球场选择，在地下输出闭馆标识
			$fresultList['gymnasium_close_result'] = 1;
		}else{

			$fresultList['gymnasium_close_result'] = 0;

			$fresultList['gymnasium_close_result'] = 0;


			//获取开闭关信息
			unset($where);
			$where['gymnasium_id'] = $gymnasium_id;
			$gymnasiumResult = $gymnasium->where($where)->find();
			$gymnasiumOpenTime = $gymnasiumResult['gymnasium_open_time'];
			$gymnasiumCloseTime = $gymnasiumResult['gymnasium_close_time'];
			$openHours = $gymnasiumCloseTime - $gymnasiumOpenTime;

			//整合球场信息
			$resultList = array();
			$sresultList = array();
			unset($where);
			$where['court_gymnasium_id'] = $gymnasium_id;
			$courtResult = $court->where($where)->limit($start_p, $e_page_num)->select();
			$courtResultCount = $court->where($where)->count();
			//对每个球场进行加载
			for($courtN = 0; $courtN < count($courtResult); $courtN++){
				$courtInfo = $courtResult[$courtN];
				$courtPassArray['court_name'] = $courtInfo['court_name'];//每个球场传往前端的信息
				unset($whereBook);
				$whereBook['court_id'] = $courtInfo['court_id'];
				$whereBook['order_date'] = $timestamp;
				$courtBookInfoList = $courtBook->where($whereBook)->order('start_time ASC')->select();
				$courtBookNumber = $courtBook->where($whereBook)->count();
				$bookInfoList = array();//对于每个球场每天预定情况数组，每个小时为一个项，0表示未被预定，1表示已被预定
				//数组初始化为0
				for($x1 = 0; $x1 < $openHours; $x1++){
					$bookInfoList[$x1] = 0;
				}
				for($bookN = 0; $bookN < $courtBookNumber; $bookN++){
					$courtBookInfo = $courtBookInfoList[$bookN];
					for($x1 = 0; $x1 < $courtBookInfo['last_units']; $x1++){
						$bookInfoList[$courtBookInfo['start_time'] - $gymnasiumOpenTime + $x1] = 1;
					}
				}
				$courtPassArray['book_info_list'] = $bookInfoList;
				$sresultList[$courtN] = $courtPassArray;
			}

			$resultList['result'] = $sresultList;
			$resultList['resultCount'] = $courtResultCount;
			$resultList['page_num'] = $page_num;
			$fresultList['resultList'] = $resultList;
		}
		$this->ajaxReturn($fresultList);
	}

	//**********球馆创建部分**********//

	/**
	 * 加载创建球馆页
	 */
	public function addGymnasium(){
		$user=$_SESSION['think_'];
        $this->assign('user',$user);
		$this->assign("biz_item_num",10);
		$this->display();
	}

	 //管理端创建球馆
	 public function addGymnasiumHandler()
	 {
		 $gymnasium=M('gymnasium_table');
		 $user_id=session('id');
		 $user = M('user_table');
		 $access=$user->where("id=%s",$user_id)->getFIeld('access');
		 /* if ($access==1 || $access==5 || $access==4)
	     { */
			 $_validate = array(
        	array('gymnasium_name', 'require', '球馆名称不能为空！'), 
			array('gymnasium_content', 'require', '球馆描述不能为空！'), 
			array('gymnasium_court_number', 'require', '球馆场地数不能为空！'), 
			array('gymnasium_open_time', 'require', '开馆时间不能为空！'), 
			array('gymnasium_close_time', 'require', '闭馆时间不能为空！'), 
			array('gymnasium_location_x', 'require', '球馆地理信息不能为空！'),
			array('gymnasium_location_province', 'require', '球馆的所属省不能为空！')
    	    );
			 
		  $upload = new \Org\Net\UploadFile();  
          $upload->maxSize = 3145728;  
          //设置文件上传类型  
          $upload->allowExts = array('jpg','gif','png','jpeg');  
          //设置文件上传位置  
          //$upload->savePath = __PUBLIC__."/Img/Uploads/";
          $upload->savePath = "./Public/Img/Uploads/gymnasiumImg/";  
          //设置文件上传名(按照时间)  
          $upload->saveRule = "time";  
          if (!$upload->upload()){  
              $this->error($upload->getErrorMsg());  
          }else
		  {  
              //上传成功，获取上传信息  
              $info = $upload->getuploadFileInfo();  			  
          } 
          $savename = $info[0]['savename'];
          $imgurl = "__PUBLIC__/Img/Uploads/gymnasiumImg/".$savename;
		  $data["gymnasium_name"] = $_POST["gymnasium_name"];
		  if ($gymnasium->where("gymnasium_name='%s'",$data["gymnasium_name"])->find()){$this->error("同名球馆已存在，请尝试在球馆名后面加上地址特征");}
		  $data["gymnasium_description"] = $_POST["gymnasium_content"];
		  $data["court_number"]=$_POST["gymnasium_court_number"];
		  $data["gymnasium_open_time"]=$_POST["gymnasium_open_time"];
		  $data["gymnasium_close_time"]=$_POST["gymnasium_close_time"];
		  $data["gymnasium_province"]=$_POST["gymnasium_location_province"];
		  $data["gymnasium_city"]=$_POST["gymnasium_location_city"];
		  $data["gymnasium_district"]=$_POST["gymnasium_location_district"];
		  $data["gymnasium_location_x"]=$_POST["gymnasium_location_x"];
		  $data["gymnasium_location_y"]=$_POST["gymnasium_location_y"];
		  $data["gymnasium_phone_number"]=$_POST["gymnasium_phone_number"];
		  $data["gymnasium_location_bref"]=$_POST["gymnasium_address"];
		  $data['gymnasium_picture']=$imgurl;
		  $data['gymnasium_open_flag']=0;//remain after add admin account
		  $data["gymnasium_master_id"]=session('id');
		  if (!$result = $gymnasium->validate($_validate)->create())
			{
				
				$this->error($gymnasium->getError());
			}
			else
			if ($gymnasium->add($data))
			{
				$this->success("添加成功");
			}
			else
			{
				/* dump($gymnasium->getLastSql());
				return; */  
				$this->error("请正确输入信息");
			}
		 /* }
		 else
		 {
			 $this->error("只有球馆主才能添加球馆");
		 } */
	 }
	
   /**
	 * 创建球馆
	 * 返回信息：
	 *     字段错误：返回对应错误信息
	 *     经纬度错误：返回1和2
	 *     添加失败：返回3
	 *     添加成功：返回0
	 *     图片上传失败：返回对应错误信息
	 */	
	/* public function createGymnasiumHandel(){
		//实例化球馆对象
		$gymnasium = D('GymnasiumTable');
		//实例化用户对象
		$user = M('user_table');

		// 自动验证 创建数据集
        if (!$data = $gymnasium->create()) {
            // 防止输出中文乱码
            header("Content-type: text/html; charset=utf-8");
            $resultList['result'] = $gymnasium->getError();
        }else{
        	//自动验证完成，接收上传图片
        	//实例化上传类
          	$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/gymnasiumImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	$resultList['result'] = $upload->getErrorMsg();  
          	}else{  
              	//上传成功，获取上传信息  
              	$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/gymnasiumImg/".$savename;
          	  	$data['gymnasium_picture'] = $imgurl;
          	  	$data['gymnasium_master_id'] = session('id');

          	 	//添加球馆
        		$result = $gymnasium->add($data);
        		if(!$result){
        			$resultList['result'] = 3;
        		}else{
        			//处理用户的access类型
        			$accessTypeOld = session('access');
        			$where['id'] = session('id');
        			if($accessTypeOld == 0){
        				session('access', 1);
        				$changeData['access'] = 1;
        				$user->where($where)->save($changeData);
        			}elseif($accessTypeOld == 2){
        				session('access', 4);
        				$changeData['access'] = 4;
        				$user->where($where)->save($changeData);
        			}elseif($accessTypeOld == 3){
        				session('access', 5);
        				$changeData['access'] = 5;
        				$user->where($where)->save($changeData);
        			}elseif($accessTypeOld == 6){
        				session('access', 7);
        				$changeData['access'] = 7;
        				$user->where($where)->save($changeData);
        			}
        			$resultList['result'] = 0;
        		}
          	}	
        }

        $this->ajaxReturn($resultList);
	}  */

	//**********球馆后台管理**********//

	/**
	 * 列表我的球馆
	 */
	 public function listMyGymnasium()
	 {
		 $user=$_SESSION['think_'];
        $this->assign('user',$user);
		 $gymnasium = M('gymnasium_table');
		 $where['gymnasium_master_id'] = session('id');
		$result = $gymnasium->where($where)->select();
		$this->data = $result;
		$this->display();
	 }
	 public function changeGym()
	 {
		$user=$_SESSION['think_'];
        $this->assign('user',$user);
		$select_gym=$_POST["gym_select"];
		$user_id=session('id');
		$this->assign("biz_item_num",13);	
	    $court=M('court_table');
		$gym=M('gymnasium_table');
		$first=$gym->where("gymnasium_name='%s'",$select_gym)->getfield('gymnasium_id');
    	$list = $court->join('thinkphp_gymnasium_table on thinkphp_court_table.court_gymnasium_id=thinkphp_gymnasium_table.gymnasium_id')->where("gymnasium_master_id=%d and gymnasium_id=%d",array($user_id,$first))->field('gymnasium_name,court_name,court_gymnasium_id,court_id')->select();
		$select=$gym->where("gymnasium_master_id=%d",$user_id)->field('gymnasium_name')->select();
		$this->assign('select',json_encode($select));
		$this->data = $list; 
		$this->display('listMyCourt');
	 }
/* 	public function listMyGymnasium(){
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的球馆条数
		$page_num = $_POST['page_num'];  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//信息查询
		$where['gymnasium_master_id'] = session('id');
		$result = $gymnasium->where($where)->field('gymnasium_id, gymnasium_name, gymnasium_location_bref, gymnasium_picture, gymnasium_phone_number')->limit($start_p, $e_page_num)->select();
		$gymnasiumCount = $gymnasium->where($where)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['gymnasium_count'] = $gymnasiumCount;
		$this->ajaxReturn($resultList);
	} */

	/**
	 * 修改球馆基本信息处理
	 *     返回值：
	 *         修改成功：1
	 *         修改失败：0
	 */
	public function changeGymnasiumInfoHandel(){
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');

		//从前台获取数据
		$data = $gymnasium->create();

        //进行信息修改
        $where['gymnasium_id'] = $data['gymnasium_id'];
        	$changeResult = $gymnasium->where($where)->save($data);

        if(!$changeResult){
        	$resultList['changeResult'] = 0;
        }else{
        	$resultList['changeResult'] = 1;
        }

        $this->ajaxReturn($resultList);
	}

	/**
	 * 重新上传球馆图片处理
	 *     返回值：
	 *         上传成功：1
	 *         上传失败：失败信息
	 *         更新数据库失败：0
	 */
	 
	public function reUploadPhotoHandel(){
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');

		//从前台获取球馆id
		$gymnasiumId = $_POST['gymnasium_id'];

		//获取原来的图片位置并实施删除
        $where['gymnasium_id'] = $gymnasiumId;
        $pictureLocation = $gymnasium->where($where)->field('gymnasium_picture')->find();
        if($pictureLocation){
        	unlink($pictureLocation);
        }

		//实例化上传类
        $upload = new \Org\Net\UploadFile();
        $upload->maxSize = 3145728;
        //设置文件上传类型  
        $upload->allowExts = array('jpg','gif','png','jpeg');  
        //设置文件上传位置  
        //$upload->savePath = __PUBLIC__."/Img/Uploads/";
        $upload->savePath = "./Public/Img/Uploads/gymnasiumImg/";  
        //设置文件上传名(按照时间)  
        $upload->saveRule = "time";
        if (!$upload->upload()){  
            $resultList['result'] = $upload->getErrorMsg();  
        }else{  
            //上传成功，获取上传信息  
            $info = $upload->getUploadFileInfo();
            $savename = $info[0]['savename'];
          	$imgurl = "__PUBLIC__/Img/Uploads/gymnasiumImg/".$savename;
          	$data['gymnasium_picture'] = $imgurl;

          	//刷新数据库
          	$refreshResult = $gymnasium->where($where)->save($data);

          	//组装返回数据
          	if(!$refreshResult){
          		$resultList['result'] = 0;
          	}else{
          		$resultList['result'] = 1;
          	}
        }

        $this->ajaxReturn($resultList);
	}

	/**
	 * 球馆停馆操作处理
	 * 返回值：
	 *     自动检测错误：对应错误信息
	 *     闭馆开始时间冲突：1
	 *     添加闭馆失败：3
	 */
	public function closeGymnasiumHandel(){
		//实例化球馆闭馆对象
		$gymnasiumClose = D('GymnasiumCloseTable');

		// 自动验证 创建数据集
        if (!$data = $gymnasium->create()) {
            // 防止输出中文乱码
            header("Content-type: text/html; charset=utf-8");
            $resultList['result'] = $gymnasium->getError();
        }else{
        	$gymnasiumId = $data['gymnasium_id'];
        	//检验闭馆开始时间冲突
        	$where['gymnasium_id'] = $gymnasiumId;
        	$where['close_start_time'] = array('lt',$data['close_start_time']);
        	$where['close_end_time'] = array('gt',$data['close_start_time']);
        	$findResult = $gymnasiumClose->where($where)->find();
        	if($findResult){
        		$resultList['result'] = 1;
        	}else{
        		//检验闭馆结束时间冲突
        		unset($findResult);
        		$where['close_start_time'] = array('lt',$data['close_end_time']);
        		$where['close_end_time'] = array('gt',$data['close_end_time']);
        		$findResult = $gymnasiumClose->where($where)->find();
        		if($findResult){
        			$resultList['result'] = 2;
        		}else{
        			//添加闭馆信息
        			$addResult = $gymnasiumClose->add($data);
        			if(!$addResult){
        				$resultList['result'] = 3;
        			}else{
        				$resultList['result'] = 0;
        			}
        		}
        	}
        }

        $this->ajaxReturn($resultList);
	}

	/**
	 * 关闭停馆处理
	 * 返回值：
	 *     关闭停馆成功：0
	 *     球馆已处于开馆状态：1
	 *     删除数据失败：2
	 */
	public function stopCloseGymnasiumHandel(){
		//实例化球馆闭馆对象
		$gymnasiumClose = D('GymnasiumCloseTable');

		//从前端获取球馆id
		$gymnasiumId = $_POST['gymnasium_id'];

		//获取当前时间戳
		$nowTimestamp = time();

		//判断当前球馆状态
		$where['gymnasium_id'] = $gymnasiumId;
        $where['close_start_time'] = array('lt',$nowTimestamp);
        $where['close_end_time'] = array('gt',$nowTimestamp);
        $findResult = $gymnasiumClose->where($where)->find();
        if(!$findResult){
        	$resultList['result'] = 1;
        }else{
        	//删除闭馆信息
        	$deleteResult = $gymnasiumClose->where($where)->delete();
        	if(!$deleteResult){
        		$resultList['result'] = 2;
        	}else{
        		$resultList['result'] = 0;
        	}
        }

        $this->ajaxReturn($resultList);
	}

	/**
	 * 列出球场信息
	 */
	 public function listMyCourt()
	 {
		$user=$_SESSION['think_'];
        $this->assign('user',$user);
		$user_id=session('id');
		$this->assign("biz_item_num",13);	
	    $court=M('court_table');
		$gym=M('gymnasium_table');
		$first=$gym->where("gymnasium_master_id=%d",$user_id)->limit(1)->getfield('gymnasium_id');
    	$list = $court->join('thinkphp_gymnasium_table on thinkphp_court_table.court_gymnasium_id=thinkphp_gymnasium_table.gymnasium_id')->where("gymnasium_master_id=%d and gymnasium_id=%d",array($user_id,$first))->field('gymnasium_name,court_name,court_gymnasium_id,court_id')->select();
		$select=$gym->where("gymnasium_master_id=%d",$user_id)->field('gymnasium_name')->select();
		/* dump($list);
		return; */ 
		$this->assign('select',json_encode($select));
		$this->data = $list; 
    	$this->display(); 
	 }
 	public function listCourt(){
		//从前端获取球馆id
		$gymnasiumId = $_POST['gymnasium_id'];

		//实例化球场对象
		$court = M('court_table');

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的球馆条数
		$page_num = $_POST['page_num'];  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//列表球场
		$where['court_gymnasium_id'] = $gymnasiumId;
		$listResult = $court->where($where)->limit($start_p, $e_page_num)->select();
		$listCount = $court->where($where)->count();

		$resultList['result'] = $listResult;
		$resultList['result_count'] = $listCount;
		$resultList['page_num'] = $page_num;
		$this->ajaxReturn($resultList);
	}

	
	 //管理端添加球场
	public function addCourt()
	{
		$user=$_SESSION['think_'];
        $this->assign('user',$user);
		$this->assign("biz_item_num",12);
		$this->display();
	}
	/**
	 * 添加球场处理
	 * 返回值：
	 *     球场名以存在：1（同一球馆的球场不能同名）
	 *     添加失败：2
	 */
	public function addCourtHandel(){
		//实例化球场对象
		$court = M('court_table');
        $gym=M('gymnasium_table');
		//从前端获取所需数据
		$_validate = array(
        	array('court_name', 'require', '球场名称不能为空！'), 
			array('court_gymnasium_id', 'require', '球馆主不能为空！'), 
			
    	    );
		$data["court_name"]=$_POST["court_name"];
        $data["court_gymnasium_id"]=$_POST["court_gymnasium_id"];
		$master_id=session('id');
		$own=$gym->where("gymnasium_master_id='%s' and gymnasium_id='%s'",array($master_id,$data["court_gymnasium_id"]))->find();
		/* dump($own);
		return; */
		if ($own)
		{
		//判断球场名重复性
		$where['court_name'] = $data['court_name'];
		$where['court_gymnasium_id'] = $data['court_gymnasium_id'];
		$findName = $court->where($where)->find();
		if($findName ){
			$this->error("该球馆已存在同名球场");
			//$resultList['result'] = 1;
		}else{
			//添加球场
			if (!$addResult = $court->validate($_validate)->create())
			{
				$this->error($court->getError());
				//$resultList['result'] = 2;
			}
			if (!$court->add($data))
			{
				$this->error("请正确输入球馆信息");
			}
			else{
				$this->success("添加成功");
				//$resultList['result'] = 0;
			}
		}
        }
		else{$this->error("您并不是该球馆的拥有者");}
		//$this->ajaxReturn($resultList);
	}

	/**
	 * 删除球场处理
	 * 返回值：
	 *     删除失败：0
	 *     删除成功：1
	 */
	public function deleteCourt(){
		//实例化球场对象
		$court = M('court_table');

		//从前端获取球馆id
		$where['court_gymnasium_id'] = $_POST['court_gymnasium_id'];
		//从前端获取球场id
		$where['court_id'] = $_POST['court_id'];
        $book_table=M('court_book_table');
		$is_book=$book_table->where("court_id='%d'",$where['court_id'])->select();
		
		if (!$is_book)
		{
		$deleteResult = $court->where($where)->delete();
		$resultList['msg'] = 0;
		}else{
			$resultList['msg'] = 1;
		}
		$this->ajaxReturn($resultList);
	}

	/**
	 * 显示球场当天可用情况
	 * resultLsit：
	 *     0：闭馆
	 *     1：开馆
	 */
	public function showCourtAvalible(){
		//从前端获取球场id
		$courtId = $_POST['court_id'];
		//实例化球场预约对象
		$courtBook = M('court_book_table');
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		//实例化停馆对象
		$gymnasiumClose = M('gymnasium_close_table');

		//从前端获取日期时间戳
		$timestamp = $_POST['date_timestamp'];
		//从前端获取球馆id
		$gymnasium_id = $_POST['gymnasium_id'];

		$resultList = array();

		//组装查询条件
		$where['close_start_time'] = array('lt', $timestamp);
		$where['close_end_time'] = array('gt', $timestamp);
		$where['gymnasium_id'] = $gymnasium_id;
		//查询闭馆信息
		$result = $gymnasiumClose->where($where)->find();

		//如果不闭馆加载球场信息
		if($result){
			//当球馆停馆时不加载球场信息，在底下下输出闭馆标识
			$resultList['gymnasium_close_result'] = 1;
		}else{
			$resultList['gymnasium_close_result'] = 0;

			//获取开闭关信息
			unset($where);
			$where['gymnasium_id'] = $gymnasium_id;
			$gymnasiumResult = $gymnasium->where($where)->find();
			$gymnasiumOpenTime = $gymnasiumResult['gymnasium_open_time'];
			$gymnasiumCloseTime = $gymnasiumResult['gymnasium_close_time'];
			$openHours = $gymnasiumCloseTime - $gymnasiumOpenTime;

			//组装可用性数组
			$whereBook['court_id'] = $courtId;
			$whereBook['order_date'] = $timestamp;
			$courtBookInfoList = $courtBook->where($whereCourt)->order('start_time ASC')->select();
			$courtBookNumber = $courtBook->where($whereCourt)->count();
			$bookInfoList = array();//对于每个球场每天预定情况数组，每个小时为一个项，0表示未被预定，1表示已被预定
			//数组初始化为0
			for($x1 = 0; $x1 < $openHours; $x1++){
				$bookInfoList[$x1] = 0;
			}
			for($bookN = 0; $bookN < $courtBookNumber; $bookN++){
				$courtBookInfo = $courtBookInfoList[$bookN];
				for($x1 = 0; $x1 < $courtBookInfo['last_units']; $x1++){
					$bookInfoList[$courtBookInfo['start_time'] - $gymnasiumOpenTime + $x1] = 1;
				}
			}
			$resultList['book_info_list'] = $bookInfoList;
		}

		$this->ajaxReturn($resultList);
	}

	/**
	 * 添加球场不可用信息
	 * 返回值：
	 *     起始时间早于开馆时间：1
	 *     结束时间晚于闭馆时间：2
	 *     起始时间冲突：3
	 *     持续时长冲突：4
	 *     添加不可用信息失败：5
	 */
	public function addCourtInavalible(){
		//实例化球场预约对象
		$courtBook = M('court_book_table');
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');

		//从前端获取数据
		$data = $courtBook->create();
		//从前端获取球馆id
		$gymnasium_id = $_POST['gymnasium_id'];

		$data['booker_id'] = session('id');

		$resultList = array();

		//获取开闭关信息
		$where['gymnasium_id'] = $gymnasium_id;
		$gymnasiumResult = $gymnasium->where($where)->find();
		$gymnasiumOpenTime = $gymnasiumResult['gymnasium_open_time'];
		$gymnasiumCloseTime = $gymnasiumResult['gymnasium_close_time'];
		$openHours = $gymnasiumCloseTime - $gymnasiumOpenTime;

		//判断开闭关冲突
		$resultList['result'] = 0;
		if($data['start_time'] < $gymnasiumOpenTime){
			$resultList['result'] = 1;
		}elseif($data['start_time'] + $data['last_units'] > $gymnasiumCloseTime){
			$resultList['result'] = 2;
		}

		if($resultList['result'] == 0){
			//判断不可用起始时间冲突
			//判断起始时间冲突
			unset($where);
			$where['start_time'] = array('lt',$data['start_time']);
			$where['court_id'] = $data['court_id'];
			$where['order_date'] = $data['order_date'];
			$findStartResult = $courtBook->where($where)->find();
			if($findStartResult){
				if(($findStartResult['start_time'] + $findStartResult['last_units']) > $data['start_time']){
					$resultList['result'] = 3;
				}else{
					$resultList['result'] = 0;
				}
			}

			//判断结束时间冲突
			if($resultList['result'] == 0){
				unset($where);
				$where['start_time'] = array('lt',$data['start_time'] + $data['last_units']);
				$where['court_id'] = $data['court_id'];
				$where['order_date'] = $data['order_date'];
				$findEndResult = $courtBook->where($where)->find();
				if($findEndResult){
					if(($findEndResult['start_time'] + $findEndResult['last_units']) > ($data['start_time'] + $data['last_units'])){
						$resultList['result'] = 4;
					}else{
						$resultList['result'] = 0;
					}
				}
			}

			//插入不可用数据
			if($resultList['result'] == 0){
				$addResult = $courtBook->add($data);
				if(!$addResult){
					$resultList['result'] = 5;
				}else{
					$resultList['result'] = 0;
				}
			}
		}

		$this->ajaxReturn($resultList);
	}

	/**
	 * 删除球馆处理
	 * 返回值：
	 *     删除失败：0
	 *     删除成功：1
	 */
	public function deleteGymnasiumHandel(){
		//实例化球馆对象
		$gymnasium = M('gymnasium_table');
		//实例化用户对象
		$user = M('user_table');

		//从前台过去球馆id
		$gymnasiumId = $_POST['gymnasium_id'];
		//从session获取球馆主id
		$masterId = session('id');

		//删除球馆
		$where['gymnasium_id'] = $gymnasiumId;
		$where['gymnasium_master_id'] = $masterId;
		$deleteResult = $gymnasium->where($where)->delete();

		if(!$deleteResult){
			$resultList['result'] = 0;
		}else{
			//判断会长特性
			unset($where);
			$where['gymnasium_master_id'] = $masterId;
			$gymnasiumCount = $gymnasium->where($where)->count();
			if($gymnasiumCount == 0){
				$accessType = session('access');
				unset($where);
				$where['id'] = session('id');
				if($accessType == 1){
					session('access', 0);
					$data['access'] = 0;
					$user->where($where)->save($data);
				}elseif($accessType == 4){
					session('access', 2);
					$data['access'] = 2;
					$user->where($where)->save($data);
				}elseif($accessType == 5){
					session('access', 3);
					$data['access'] = 3;
					$user->where($where)->save($data);
				}elseif($accessType == 7){
					session('access', 6);
					$data['access'] = 6;
					$user->where($where)->save($data);
				}
			}

			$resultList['result'] = 1;
		}

		$this->ajaxReturn($resultList);
	}
	public function getBooker()
    {
		$court_id=$_POST['court_id'];
		$apply=M('court_book_table');
		$booker=$apply->join('thinkphp_user_table on thinkphp_court_book_table.booker_id=thinkphp_user_table.id')->where("court_id='%d'",$court_id)->field('name,start_time,last_units')->select();
		$resultList["result"]=$booker;
		$this->ajaxReturn($resultList);
	}
	public function gymnasiumDetail()
	{
		$gymnasium_id=$_POST['gymnasium_id'];
		$user_id=session('id');
		$gymnasium=M('gymnasium_table');
		$result=$gymnasium->where("gymnasium_id='%d'",$gymnasium_id)->find();
		$status=$gymnasium->where("gymnasium_id='%d'",$gymnasium_id)->getField('gymnasium_open_flag');
		$resultList["result"]=$result;
		$resultList['msg'] = $status;
		$this->ajaxReturn($resultList);
	}
	public function updateGymnasium()
	{
		if (IS_POST) {
		  if (!session('id')) $this->error("请先登录");
		  $upload = new \Org\Net\UploadFile();  
          $upload->maxSize = 3145728;  
          //设置文件上传类型  
          $upload->allowExts = array('jpg','gif','png','jpeg');  
          //设置文件上传位置  
          //$upload->savePath = __PUBLIC__."/Img/Uploads/";
          $upload->savePath = "./Public/Img/Uploads/gymnasiumImg/";  
          //设置文件上传名(按照时间)  
          $upload->saveRule = "time";  
          if (!$upload->upload()){  
          }else{  
              //上传成功，获取上传信息  
              $info = $upload->getuploadFileInfo();
              $savename = $info[0]['savename'];
              $imgurl = "__PUBLIC__/Img/Uploads/gymnasiumImg/".$savename;
              $data['gymnasium_picture']=$imgurl;			  
          }
          
		$gymnasium=M('gymnasium_table');
		$gymnasium_id = $_POST["gymnasium_id"];
		if  ($_POST["gymnasium_name"]!=NULL)
		$data["gymnasium_name"] = $_POST["gymnasium_name"];
	    if  ($_POST["gymnasium_open_time"]!=NULL)
        $data["gymnasium_open_time"] = $_POST["gymnasium_open_time"]; 
	    if  ($_POST["gymnasium_close_time"]!=NULL)
        $data["gymnasium_close_time"] = $_POST["gymnasium_close_time"]; 
	    if  ($_POST["gymnasium_description"]!=NULL)
	    $data["gymnasium_description"] = $_POST["gymnasium_description"];
	     /* if  ($_POST["gymnasium_book_unit"]!=NULL)
        $data["gymnasium_book_unit"] = $_POST["gymnasium_book_unit"];  */
	    if  ($_POST["gymnaisum_court_number"]!=NULL)
		$data["court_number"]=$_POST["gymnaisum_court_number"];
        if  ($_POST["gymnasium_address"]!=NULL)
		$data["gymnasium_location_bref"]=$_POST["gymnasium_address"];
	    if  ($_POST["gymnaisum_phone_number"]!=NULL)
		$data["gymnaisum_phone_number"]=$_POST["gymnaisum_phone_number"];
	    if  ($_POST["gymnasium_location_x"]!=NULL)
		{
			$data["gymnasium_location_x"]=$_POST["gymnasium_location_x"];
			$data["gymnasium_location_y"]=$_POST["gymnasium_location_y"];
			$data["gymnasium_province"]=$_POST["gymnasium_location_province"];
			$data["gymnasium_city"]=$_POST["gymnasium_location_city"];
			$data["gymnasium_district"]=$_POST["gymnasium_location_district"];
		}
			if ($gymnasium->where("gymnasium_id='%d'",$gymnasium_id)->save($data))
			{
				$this->success("修改成功");
			}
			
		}
	}
}